<?php

/**
 * JavaScript code snipped.
 *
 * @author Ian Clarence <ian.clarence@gmail.com>
 */
class ViewCodeSnippet {

    /**
     * The prefix.
     */
    const PREFIX = ':';

    /**
     * The JavaScript string.
     *
     * @var string
     */
    private $js;

    /**
     * The constructor.
     *
     * @param string $js
     */
    public function __construct($js) {
        $this->js = $js;
    }

    /**
     * Binding a variable to the JavaScript.
     *
     * @param string $key
     * @param string $variable
     * @param bool $addQuotes
     * @param bool $escape
     * @param Object $object
     * @param callback $escapeFunction
     * @return bool
     */
    public function bindVariable(
        $key,
        $variable,
        $addQuotes = TRUE,
        $escape = FALSE,
        $object = NULL,
        $escapeFunction = NULL
    ) {
        $values = explode(self::PREFIX . $key, $this->js);
        $delimiter = $addQuotes ?
            Utils::encloseInQuotes(
                $escape ?
                    call_user_func(
                        $object == NULL ? $escapeFunction : array($object, $escapeFunction),
                        $variable
                    ) :
                    $variable
            ) :
            $variable;
        if (!is_string($delimiter) && !is_numeric($delimiter) && ($delimiter != NULL)) {
            echo "<br />Key {$key}. This should be a string..<br />\n";
            Utils::dump($delimiter);
        }
        $this->js = implode($delimiter, $values);
        return count($values) > 1;
    }

    /**
     * Same as bindVariable, but instead for a simple text string.
     * Can be used for jQuery objects or field names.
     *
     * @param string $key
     * @param string $textString
     * @return bool
     */
    public function bindTextString($key, $textString) {
        $values = explode(self::PREFIX . $key, $this->js);
        $this->js = implode($textString, $values);
        return count($values) > 1;
    }

    /**
     * Viewing the JavaScript code snippet.
     * 
     * @return string
     */
    public function view() {
        return $this->js;
    }

}